import request from '@/utils/request'

export interface TaskListParams {
  userId: string | number
}

export interface TaskItem {
  taskId: number
  taskContent: string
  status: string  // 2 表示已完成
  buyType: string
}

export interface TaskListResult {
  rows: TaskItem[]
  total: number
  code: number
  msg: string
}

export interface TaskDetailResult {
  code: number
  msg: string
  data: TaskItem
}

// 获取用户任务列表
export function getUserTaskList(params: TaskListParams) {
  return request<TaskListResult>({
    url: '/system/userTasks/list',
    method: 'GET',
    data: params
  })
}

// 获取单个任务详情
export function getTaskDetail(taskId: string | number, buyType: string | number) {
  return request<TaskDetailResult>({
    url: `/system/userTasks/${taskId}/${buyType}`,
    method: 'GET'
  })
}

// 上传文件接口返回结果类型
export interface UploadResult {
  code: number
  msg: string
  url: string
  fileName: string
}

// 上传文件
export function uploadFile(file: string) {
  return new Promise<UploadResult>((resolve, reject) => {
    const token = uni.getStorageSync('token')
    uni.uploadFile({
      url: import.meta.env.VITE_BASE_URL + '/common/upload',
      header: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + token
      },
      filePath: file,
      name: 'file',
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          resolve(data)
        } catch (error) {
          reject(new Error('解析响应数据失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 打卡接口
export interface TaskRecordParams {
  taskId: string | number
  recordDate: string | number
  points: number
  filesUrl: string[]
  userId: string | number
}

export function submitTaskRecord(data: TaskRecordParams) {
  return request({
    url: '/system/taskRecords',
    method: 'POST',
    data
  })
}
